<?php

namespace app\middleware;

use app\common\OsType;
use app\model\User;
use support\Cache;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class BaseRequest implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $request->os_type = OsType::OS_TYPE_WEB->value;
        $uid              = 0;
        if (empty(request()->uid)) {
            $session_id = $request->session()->getId();
            $u_token    = Cache::get(UID_SESSION_KEY . '_' . $session_id, '');
            if (!is_string($u_token)) $u_token = '';
            $request->u_token = '';
            if ($u_token) {
                $request->u_token = $u_token;
                list(, $uid) = User::parseToken($u_token);
            }
            request()->uid = intval($uid);
        }
        // ============ 来路 ============
        $ref = $request->get('ref');
        if ($ref) $request->session()->set('ref', $ref);
        return $next($request);
    }
}